import * as vscode from "vscode";
import { showErrorMessage, showInformationMessage } from "../vscode/message";
import { userDataToChat, chatjptConfig } from "@ap/webView/chatjpt";
import { arenaErrorMsg } from "../vscode/errorMsg";
import { sleep, chatjptViewSleepMs } from "../data";
import { CommandId } from "@ap/command";
import { ConfigurationItem } from "../vscode/setInsConfig";

export function insertTextAtSelection(editor: vscode.TextEditor): string {
  const selections = editor.selections;
  let text = "";
  for (const selection of selections) {
    const start = selection.start;
    const end = selection.end;
    text += editor.document.getText(new vscode.Range(start, end));
  }
  return text;
}

export default async function sendCodeToAi(
  label: string,
  type: number,
  auxiliaryText?: string,
) {
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    return;
  }
  let text = insertTextAtSelection(editor);
  if (auxiliaryText || (text && text.length > 0)) {
    if (auxiliaryText) {
      text = auxiliaryText;
    }
    const data = userDataToChat();
    if (data) {
      vscode.commands.executeCommand(CommandId.chatjpt_workbench);
      await sleep(chatjptViewSleepMs);
      if (!chatjptConfig || !chatjptConfig.view) {
        showInformationMessage("请先手动激活Chat吉PT对话界面，再使用本功能。");
        return;
      }
      chatjptConfig.view.webview.postMessage({
        type: "postFastChat",
        labelChat: label,
        typeChat: type,
        text: text,
        nickname: data.userData.data?.nickname,
        avatar: data.userData.data?.avatar,
        userId: data.userData.data?.userId,
        userData: data.userData,
        userAgnet: data.ua,
      });
    } else {
      showErrorMessage(arenaErrorMsg.LOG_IN_TO_THE_SHINJIMA_ACCOUNT);
    }
  } else {
    showInformationMessage("请选至少一段代码片段");
  }
}

export function openChatjptSetting() {
  vscode.commands.executeCommand(
    CommandId.ap_openSettings,
    "@ext:box3lab.box3arenapro " + ConfigurationItem.CHATJPT_TOOL,
  );
}
